package cn.wolfcode.postbar.redis.service.impl;


import cn.wolfcode.postbar.domain.UserInfo;
import cn.wolfcode.postbar.redis.service.IUserInfoRedisService;
import cn.wolfcode.postbar.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户缓存服务实现
 */
@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

    @Autowired
    private StringRedisTemplate template;

    @Override
    public UserInfo getUserByToken(String token) {
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        if (template.hasKey(key)) {
            //user对象json格式字符串
            String userStr = template.opsForValue().get(key);
            UserInfo userInfo = JSON.parseObject(userStr, UserInfo.class);
            //重置30分钟
            template.expire(key,RedisKeys.USER_LOGIN_TOKEN.getTime(),TimeUnit.SECONDS);
            return userInfo;
        }
        return null;
    }

    @Override
    public String setToken(UserInfo user) {
        //创建token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //key: user_login_token:token
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        //json格式字符串
        String value = JSON.toJSONString(user);
        //缓存用户对象,key 为token,value user对象
        template.opsForValue().set(key,value,RedisKeys.USER_LOGIN_TOKEN.getTime(),TimeUnit.HOURS);
        return token;
    }
}
